package com.zcunsoft.pm.note.push.email;

import com.sun.mail.util.MailSSLSocketFactory;
import com.zcunsoft.pm.note.push.ZCNotePushConfig;
import com.zcunsoft.pm.note.push.ZCPushResult;
import org.springframework.beans.factory.annotation.Autowired;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

/**
 * @author denis
 * @date 2022/6/22 15:39
 */
public class ZCMailUtils {

    public static ZCPushResult sendMail(String toEMail, String subject, String content) {
        ZCPushResult res = new ZCPushResult();
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException exception) {
            res.setCode(503);
            res.setMsg(exception.getMessage());
            return res;
        }
        //指定协议类型可以解决下述报错
        //Could not connect to SMTP host:smtp.exmail.qq.com,port:465
        properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                PasswordAuthentication pa = new PasswordAuthentication(ZCNotePushConfig.getEmailAccount(), ZCNotePushConfig.getEmailPassword());
                return pa;
            }
        });
        MimeMessage mimeMessage = null;
        try {
            mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(ZCNotePushConfig.getEmailAccount(), ZCNotePushConfig.getEmailAccount()));
        } catch (Exception e) {
            res.setCode(503);
            res.setMsg(e.getMessage());
            return res;
        }
        try {
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("test-mail@domainname.com"));
            mimeMessage.setSubject(subject);
            mimeMessage.setSentDate(new Date());
            mimeMessage.setText(content);
            mimeMessage.saveChanges();

            Transport.send(mimeMessage);
        } catch (Exception e) {
            res.setCode(503);
            res.setMsg(e.getMessage());
        }
        res.setCode(200);
        res.setMsg("success");
        return res;
    }
}
